package com.itheima.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.dubbo.config.annotation.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.mapper.PermissionMapper;
import com.itheima.pojo.Permission;
import com.itheima.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service(interfaceClass = PermissionService.class)
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public PageResult findPage(Integer currentPage, Integer pageSize, String queryString) {

        PageHelper.startPage(currentPage, pageSize);


        Example example = new Example(Permission.class);
        Example.Criteria criteria = example.createCriteria();

        if (queryString != null && queryString.trim() != "") {
            criteria.orLike("name", "%" + queryString + "%");
            criteria.orLike("keyword", "%" + queryString + "%");
        }

        List<Permission> list = permissionMapper.selectByExample(example);


        PageInfo<Permission> pageInfo = new PageInfo<>(list);

        return new PageResult(pageInfo.getTotal(), pageInfo.getList());
    }

    @Override
    public void add(Permission permission) {

        permissionMapper.insert(permission);
    }

    @Override
    public Permission findById(Integer id) {
        Permission permission = permissionMapper.selectByPrimaryKey(id);
        return permission;
    }

    @Override
    public void edit(Permission permission) {
        permissionMapper.updateByPrimaryKey(permission);
    }

    @Override
    public void deleteById(Integer id) {

        Integer count = permissionMapper.findCountByPermissionId(id);
        if (count > 0) {
            throw new RuntimeException(MessageConstant.PERMISSION_IS_QUOTED);
        }

        permissionMapper.deleteByPrimaryKey(id);
    }

}
